﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using Foothill.Bus;
using Foothill.Bus.Result;
using Foothill.Bus.Node;
using Foothill.Persistent.Command;
using Foothill.Core.FieldMapping;
using GGFW.Entity.DocumentsManage;
using GGFW.DataAccess.Constants;

namespace GGFW.DataAccess.DocumentsManage
{
    public class ClientDao : BaseDao
    {
        #region 获取客户信息
        /// <summary>
        /// 获取客户信息
        /// </summary>
        /// <param name="taskname"></param>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        public List<client> GetClientInfo(int pageSize, int pageNo, string client_name, out int totalCount)
        {
            string condition = "where isdeleted!=1";
            if (!string.IsNullOrEmpty(client_name)) condition += string.Format(" and client_name like '%{0}%'", client_name);

            string sql = "select * from client " + condition + " ";

            totalCount = GetQueryCount(sql);

            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("client", sql);

            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.executePage(pageNo, pageSize) as ResultQueryNativeSql;

            //执行结果为空
            if (result == null)
            {
                throw new Exception(GGFW.DataAccess.Constants.Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }

            //是否存在记录
            if (result.Records != null && result.Records.Count > 0)
            {
                List<client> dataList = new List<client>();
                AbstractResultBus.CopyProperties<client>(dataList, result.Records, null);
                MappingFieldEvaluator.ProcessList<client>(dataList);
                return dataList;
            }
            return null;
        }
        #endregion

        #region 获取客户列表
        /// <summary>
        /// 获取客户列表
        /// </summary>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <param name="queryEntity"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<client> GetClientList(int PageSize, int PageIndex, client queryEntity, out int totalCount)
        {
            string querySql = this.getQuerySqlerClientList(queryEntity);

            //结果总数
            totalCount = this.GetQueryCount(querySql);

            querySql += getOrderSqlClientList(queryEntity);

            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("client", querySql);

            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.executePage(PageIndex, PageSize) as ResultQueryNativeSql;

            //执行结果为空
            if (result == null)
            {
                throw new Exception(GGFW.DataAccess.Constants.Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }

            //是否存在记录
            if (result.Records != null && result.Records.Count > 0)
            {
                List<client> list = new List<client>();
                AbstractResultBus.CopyProperties<client>(list, result.Records, null);
                return list;
            }
            return null;
        }
        /// <summary>
        /// 获得查询Sql
        /// </summary>
        /// <param name="queryEntity">查询条件实体</param>
        /// <returns>查询Sql</returns>
        private string getQuerySqlerClientList(client queryEntity)
        {
            StringBuilder sqlText = new StringBuilder();
            sqlText.Append("select * from client where isdeleted=0");
            //是否查询生产单编号
            if (queryEntity.client_id != 0)
            {
                sqlText.Append(string.Format(" and client_id = '{0}' ", queryEntity.client_id));
            }
            //是否查询生产单编号
            if (!string.IsNullOrEmpty(queryEntity.client_code))
            {
                sqlText.Append(string.Format(" and client_code like '%{0}%' ", queryEntity.client_code));
            }
            //是否查询生产单款名
            if (!string.IsNullOrEmpty(queryEntity.client_name))
            {
                sqlText.Append(string.Format(" and client_name like '%{0}%' ", queryEntity.client_name));
            }
            return sqlText.ToString();
        }
        /// <summary>
        /// 获得排序语句
        /// </summary>
        /// <param name="queryEntity">查询条件</param>
        /// <returns>排序语句</returns>
        private string getOrderSqlClientList(client queryEntity)
        {
            string OrderField = "";
            if (!string.IsNullOrEmpty(queryEntity.OrderField))
            {
                OrderField = "client." + queryEntity.OrderField;
            }
            return SqlUtil.GetOrderSql(OrderField, queryEntity.OrderDirection, "client.client_id", "desc");
        }
        #endregion

        #region 保存客户信息
        /// <summary>
        /// 保存客户信息
        /// </summary>
        /// <param name="productFileds"></param>
        /// <returns></returns>
        public int SaveClient(string clientFileds)
        {
            int client_id = 0;
            string sql = "Insert into client({0}) values({1});select @@IDENTITY";
            string[] filed_NameValue = clientFileds.Split('ξ');
            string filed_Name = filed_NameValue[0];
            string filed_Value = filed_NameValue[1];
            sql = string.Format(sql, filed_Name, filed_Value);
            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("client", sql);

            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.execute() as ResultQueryNativeSql;

            //执行结果为空
            if (result == null)
            {
                throw new Exception(Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }

            //是否存在记录
            if (result.Records != null && result.Records.Count > 0)
            {
                client_id = Convert.ToInt32(result.Records[0].Fields[0].FieldValue);
            }

            return client_id;
        }
        #endregion

        #region 更新客户信息
        /// <summary>
        /// 更新客户信息
        /// </summary>
        /// <param name="ClientID"></param>
        /// <param name="FiledName"></param>
        /// <param name="FiledValue"></param>
        /// <returns></returns>
        public bool UpdateClientInfo(string ClientID, string FiledName, string FiledValue)
        {
            string sql = string.Format("update client set {0}='{1}' where client_id={2}", FiledName, FiledValue, ClientID);


            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("client", sql);


            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.execute() as ResultQueryNativeSql;

            //执行结果为空
            if (result == null)
            {
                throw new Exception(Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }

            return true;
        }
        #endregion

        #region 删除客户
        /// <summary>
        /// 删除客户
        /// 并不真正删除，只是将isdeleted置为1
        /// </summary>
        /// <param name="client_id"></param>
        public void DelClientByID(int client_id)
        {
            string sql = string.Format("update client set isdeleted=1 where client_id='{0}'", client_id);
            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("client", sql);


            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.execute() as ResultQueryNativeSql;

            //执行结果为空
            if (result == null)
            {
                throw new Exception(GGFW.DataAccess.Constants.Common.UNKNOW_DB_ERROR);
            }
            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }
        }
        #endregion
    }
}
